<template>
  <div>
    <input type="file" @change="handleFileChange" />
    <button @click="convertPdfToWord">转换</button>
    <button v-if="downloadLink" @click="downloadConvertedFile">下载</button>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  data () {
    return {
      pdfFile: null,
      downloadLink: null
    }
  },
  methods: {
    handleFileChange (event) {
      this.pdfFile = event.target.files[0]
      this.downloadLink = null // Reset download link when selecting a new file
    },
    convertPdfToWord () {
      const formData = new FormData()
      formData.append('file', this.pdfFile)

      axios.post('http://127.0.0.1:8799/convert4', formData, {
        responseType: 'arraybuffer',
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
        .then(response => {
          const blob = new Blob([response.data], { type: 'application/msword' })
          this.downloadLink = URL.createObjectURL(blob)
        })
        .catch(error => {
          console.error('Error converting PDF to Word:', error)
        })
    },
    downloadConvertedFile () {
      const link = document.createElement('a')
      link.href = this.downloadLink
      const originalFileName = this.pdfFile.name
      const fileNamePrefix = originalFileName.substring(0, originalFileName.lastIndexOf('.'))

      // Set the download attribute with the new file name
      link.download = `${fileNamePrefix}.doc`
      link.click()
    }
  }
}
</script>
